package com.wmy.luckywheel.controller;

import com.wmy.luckywheel.entity.Result;
import com.wmy.luckywheel.entity.po.Prize;
import com.wmy.luckywheel.entity.po.Record;
import com.wmy.luckywheel.service.PrizeService;
import com.wmy.luckywheel.service.RecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Sian37
 * 抽奖控制器
 */
@Slf4j
@RestController
@RequestMapping("/lottery")
@RequiredArgsConstructor
public class LotteryController {

    private final PrizeService prizeService;
    private final RecordService recordService;

    @GetMapping
    public Result<Prize> lottery() {
        log.info("抽奖");

        List<Prize> prizes = prizeService.queryList();

        // 生成时间戳（毫秒数）
        long timestamp = System.currentTimeMillis();
        log.info("抽奖时间戳：{}", timestamp);

        // 直接使用整数概率值（假设percent存储的是1-100的整数值）
        long totalProbability = prizes.stream()
                .mapToLong(Prize::getPercent)
                .sum();

        // 计算奖品在哪个区间
        long randomValue = timestamp % totalProbability;

        Prize prize = new Prize();
        int t = 0;
        // 查看随机值在哪个奖品区间
        for(int i = 0; i < prizes.size(); i++){
            t += prizes.get(i).getPercent();
            if(randomValue <= t){
                prize =  prizes.get(i);
                break;
            }
        }
        //将这个奖品的概率除以2
        if(prize.getPercent() >= 2){
            prize.setPercent(prize.getPercent() / 2);
        }
        //更新这个奖品的概率
        prizeService.update(prize);
        //将这个抽奖的结果保存在 中奖的数据库中
        Record record = new Record();
        record.setName(prize.getName());
        record.setPrizeId(prize.getId());
        record.setCreateTime(LocalDateTime.now());
        recordService.add(record);
        return Result.success(prize);
    }
}
